package com.one2manycall.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/files")
@Slf4j
public class FileUploadController {


    private static final Tika tika = new Tika();

    private static final String UPLOAD_DIR = "uploads/";
    private static final List<String> VIDEO_MIME_TYPES = Arrays.asList(
            "video/mp4", "video/mpeg", "video/quicktime", "video/x-msvideo",
            "video/x-flv", "video/webm", "video/3gpp", "video/3gpp2"
    );

    // Ensure the upload.html directory exists
    static {
        Path dirPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(dirPath)) {
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {

                log.error(e.getLocalizedMessage());
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file,
                                                   @RequestParam("filename") String customFileName,
                                                   @RequestParam("userName") String userName,
                                                   @RequestParam("token") String token
    ) {

        log.info("start upload.html data!!! ");
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a video file to upload.html.");
        }

        if (userName.isEmpty()) {
            return ResponseEntity.badRequest().body("userName require ");
        }

        if (token.isEmpty()) {
            return ResponseEntity.badRequest().body("not login ");
        }


        // Sanitize the filename to avoid path traversal attacks
        String sanitizedFileName = sanitizeFileName(customFileName);

        // Check file content type instead of relying on extension or Content-Type header
        try {

            // Detect the MIME type using Apache Tika
            String actualFileType = tika.detect(file.getInputStream());


            if (!VIDEO_MIME_TYPES.contains(actualFileType)) {
                return ResponseEntity.badRequest().body("Only video files are allowed.");
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Failed to determine file type: " + e.getMessage());
        }

        try {
            // Save the file locally with the sanitized name and original extension
            String fileExtension = getFileExtension(file.getOriginalFilename());
            Path serverFilePath = Paths.get(UPLOAD_DIR, sanitizedFileName + "." + fileExtension);
            FileCopyUtils.copy(file.getBytes(), Files.newOutputStream(serverFilePath));

            return ResponseEntity.ok("You successfully uploaded " + sanitizedFileName + "!");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Failed to upload.html " + customFileName + " => " + e.getMessage());
        }
    }

    private String sanitizeFileName(String fileName) {
        // Remove all non-alphanumeric characters except for hyphens and underscores
        return fileName.replaceAll("[^a-zA-Z0-9-_]", "");
    }

    private String getFileExtension(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf('.') + 1);
        } else {
            return "";
        }
    }
}